package com.example.pplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {
    private ListView lvTasks;
    private FloatingActionButton fabAddTask;
    private TabLayout tabLayout;
    private TaskManager taskManager;
    private SimpleCursorAdapter adapter;
    private long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 深色模式适配
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        boolean darkMode = prefs.getBoolean("dark_mode", false);
        AppCompatDelegate.setDefaultNightMode(
                darkMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO
        );

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取当前用户ID
        currentUserId = getCurrentUserId();
        taskManager = new TaskManager(this, currentUserId);

        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 初始化视图
        lvTasks = findViewById(R.id.lv_tasks);
        fabAddTask = findViewById(R.id.fab_add_task);
        tabLayout = findViewById(R.id.tab_layout);

        // 设置适配器
        String[] from = {DBHelper.COLUMN_TITLE, DBHelper.COLUMN_PRIORITY};
        int[] to = {android.R.id.text1, android.R.id.text2};
        adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2,
                null, from, to, 0);
        lvTasks.setAdapter(adapter);

        // 添加选项卡
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("今日"));
        tabLayout.addTab(tabLayout.newTab().setText("高优先级"));
        tabLayout.addTab(tabLayout.newTab().setText("已完成"));

        // 默认加载全部任务
        refreshTaskList("all");

        // 添加任务按钮点击事件
        fabAddTask.setOnClickListener(v -> {
            startActivityForResult(new Intent(this, AddTaskActivity.class), 1);
        });

        // 列表项点击事件
        lvTasks.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(this, TaskDetailActivity.class);
            intent.putExtra("task_id", id);
            startActivity(intent);
        });

        // 选项卡切换事件
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        refreshTaskList("all"); // 全部任务
                        break;
                    case 1:
                        refreshTaskList("today"); // 今日任务
                        break;
                    case 2:
                        refreshTaskList("high_priority"); // 高优先级
                        break;
                    case 3:
                        refreshTaskList("completed"); // 已完成
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void refreshTaskList(String filter) {
        Cursor cursor = taskManager.getTasksByFilter(filter);
        adapter.changeCursor(cursor);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            refreshTaskList("all");
        }
    }

    private long getCurrentUserId() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        return prefs.getLong("current_user_id", -1); // 如果没有找到用户ID，返回-1
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        } else if (id == R.id.action_logout) {
            logoutUser();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 添加退出登录方法
    private void logoutUser() {
        // 清除SharedPreferences中的用户信息
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove("current_user_id");
        editor.apply();

        // 跳转到登录界面
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}